package edu.hcmus.sow.dao;

import java.util.List;

import org.hibernate.criterion.Restrictions;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import edu.hcmus.sow.domain.Folder;

/**
 * DAO to manage Folder entities.
 * 
 */
@Repository
@Transactional
public class FolderDAOImpl extends AbstractHibernateDAO<Folder, Integer> implements FolderDAO {

   public List<Folder> getByClientID(Integer clientID) throws DataAccessException {
      List<Folder> list = findByCriteria(Restrictions.eq("clientID", clientID), Restrictions.isNull("parentID"));
      return list;
   }

   public List<Folder> getByParentID(Integer parentID) throws DataAccessException {
      List<Folder> list = findByCriteria(Restrictions.eq("parentID", parentID));
      return list;
   }

   public boolean isExist(Integer clientID, Integer parentID, String name) throws DataAccessException {
      List<Folder> list = findByCriteria(Restrictions.eq("parentID", parentID), Restrictions.eq("name", name),
            Restrictions.eq("clientID", clientID));

      if (list.isEmpty()) {
         return false;
      }
      return true;
   }

   public List<Folder> getRepositories(Integer clientID) throws DataAccessException {
      String query = "from Folder f join fetch f.userByCreatedBy u ";
      query += "where f.clientID = ? and f.parentID is null";
      return executeQuery(query, clientID);
   }

   public List<Folder> findFolderByName(Integer clientID, String name) throws DataAccessException {
      return findByCriteria(Restrictions.eq("clientID", clientID), Restrictions.eq("name", name),
            Restrictions.isNull("parentID"));
   }
}
